import React, { Component, Fragment } from 'react'
import TodoItem from './TodoItem'
import Test from './Test'
import './style.css'

export class TodoList extends Component {

  constructor(props) {
    super(props);
    this.state = {
      inputValue: '',
      list: []
    };
    this.handleInputValue = this.handleInputValue.bind(this);
    this.handleBtnClick = this.handleBtnClick.bind(this);
    this.handleItemDelete = this.handleItemDelete.bind(this);
  }

  render() {
    return (
      <Fragment>
        <div>
          <label htmlFor="insertArea">输入内容</label>
          <input
            id="insertArea"
            className="input"
            value={this.state.inputValue}
            onChange={this.handleInputValue}
            ref={(input) => { this.input = input }}
          />
          <button onClick={this.handleBtnClick}>提交</button>
        </div>
        <ul>
          {this.getTodoItem()}
        </ul>
        <Test content={this.state.inputValue}/>
      </Fragment>
    )
  }
  // 获取input值
  handleInputValue() {
    const value = this.input.value
    //异步操作 先把值存储
    this.setState(() => ({
      inputValue: value
    }))
  }
  //   点击事件
  handleBtnClick() {
    //prevState 可直接用之前的状态
    this.setState((prevState) => ({
      list: [...prevState.list, prevState.inputValue],
      inputValue: ''
    }), () => {
      //setState异步，完成后执行
    })
  }
  //  删除item
  handleItemDelete(index) {
    this.setState(() => {
      const list = [...this.state.list];
      list.splice(index, 1)
      return { list }
    })
  }
  getTodoItem(){
    return this.state.list.map((item, index) => {
      return (
        <TodoItem
          content={item}
          index={index}
          key={index}
          deleteItem={this.handleItemDelete}
        />
      )
    })
  }
}

export default TodoList;
